package com.wfm.leetcode.editor.cn;

import java.util.Arrays;

/**
 * 三个条件最终则算：
 * 0______x/2___+7____x__________
 *       x       |  √  |    x
 *           只有在这个区间才会加好友
 * nlogn=排序o(nlogn)+遍历数组以及使用双指针o(n)
 * logn=排序的栈空间logn
 */
public class PEight25适龄的朋友{
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int numFriendRequests(int[] ages) {
        Arrays.sort(ages);
        int n = ages.length;
        int res = 0;
        int left = 0,right = 0;
        for (int age:ages){
            if(age<15) continue;
            while (ages[left]<=0.5*age+7){
                left++;
            }
            while (right+1<n&&ages[right+1]<=age){
                right++;
            }
            res+=right-left;
        }
        return res;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

    public static void main(String[] args) { 
        Solution solution = new PEight25适龄的朋友().new Solution();
        int i = solution.numFriendRequests(new int[]{20,30,100,110,120});
        System.out.println(i);
        System.out.println(solution.numFriendRequests(new int[]{16, 17, 18}));
        System.out.println(solution.numFriendRequests(new int[]{16,16}));

    }

    public int numFriendRequestsMy(int[] ages) {
        int res = 0;
        for (int i = 0; i < ages.length; i++) {
            int sum = 0;
            for (int j = 0; j < ages.length; j++) {
                if(i==j) continue;
                if(ages[j]<=0.5*ages[i]+7){
                    continue;
                }
                if(ages[j]>ages[i]){
                    continue;
                }
                if(ages[j]>100&&ages[i]<100){
                    continue;
                }
                sum++;
            }
            res+=sum;
        }
        return res;
    }
}